package main

import (
	"fmt"
	"gitee.com/scottq/go-framework/src/miscs"
	v1 "gitee.com/scottq/go-framework/src/v1"
	v1http "gitee.com/scottq/go-framework/src/v1/httpserver"
	v1job "gitee.com/scottq/go-framework/src/v1/jobserver"
	v1log "gitee.com/scottq/go-framework/src/v1/log"
	v1rpc "gitee.com/scottq/go-framework/src/v1/rpcserver"
	"google.golang.org/grpc"
	"os"
	"path/filepath"
	"time"
)

func main() {
	logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0]))

	//log
	logger := v1log.NewZapLog("exampleApp", logPath, nil)

	//创建一个http server
	server1 := getHttpServer(logger)

	//创建 job server
	job1 := getJobServer(logger)
	runner := getJobRunner(logger)
	scheduler := getJobScheduler(logger)

	//创建 rpc server
	server2:=getGRPCServer(logger)

	app, err := v1.NewApp(
		"exampleApp",
		v1.WithAppOpsLog(logger),
		v1.WithAppOpsStopTimeout(time.Second*5),
		v1.WithAppOpsVersion("1.0"),

		v1.WithAppOpsServer(server1), //将其放入app中
		v1.WithAppOpsServer(job1),    //将其放入app中
		v1.WithAppOpsServer(runner),    //将其放入app中
		v1.WithAppOpsServer(scheduler),    //将其放入app中
		v1.WithAppOpsServer(server2),    //将其放入app中
	)
	if err != nil {
		logger.Fatal(fmt.Sprintf("new app error:%s", err))
		return
	}

	go func() {
		time.Sleep(time.Second * 10)
		logger.Info("stop server")
		server1.Stop()
	}()

	err = app.Run()
	if err != nil {
		logger.Fatal("app running error: " + err.Error())
	}

}

func getGRPCServer(logger v1log.ILog) *v1rpc.GRPCServer {
	server, err := v1rpc.NewGRPCServer("exampleHttpServer", ":8080", func(server *grpc.Server) {

	})
	if err != nil {
		logger.Error("run http server error:%s" + err.Error())
		panic(err)
	}
	server.AddLogger(logger)

	return server
}

func getHttpServer(logger v1log.ILog) *v1http.HttpServer {
	httpServer, err := v1http.NewHttpServer("exampleHttpServer", ":8080")
	if err != nil {
		logger.Error("run http server error:%s" + err.Error())
		panic(err)
	}
	httpServer.AddLogger(logger)
	httpServer.RouteGet("/v1", func(ctx *v1http.Ctx) {
		ctx.WriteStr("Hello World")
	}, []v1http.Middleware{})

	return httpServer
}

func getJobServer(logger v1log.ILog) *v1job.Job {
	//创建一个job
	job := v1job.NewJob("printX", func() {
		logger.Info("job: " + time.Now().Format(miscs.DateTimeLayout))
	})
	job.SetCoNum(2)
	job.AddLogger(logger)
	return job
}

func getJobRunner(logger v1log.ILog) *v1job.JobRunner{
	runner := v1job.NewJobRunner("mixJobs")
	//只执行一次
	runner.AddExecute("printTime", func() {
		println("executor", time.Now().Format(miscs.DateTimeLayout))
	})
	return runner
}

func getJobScheduler(logger v1log.ILog) *v1job.JobScheduler {
	job := v1job.NewJob("", func() {
		logger.Info("job: " + time.Now().Format(miscs.DateTimeLayout))
	})

	//创建一个scheduler
	scheduler := v1job.NewJobScheduler("scheduler", time.Second*2, job)
	return scheduler
}
